﻿using Authority.Model;
using AutoMapper.DTO;
using Common.Library;
using Dapper.Library;
using Dapper.MsSql.Library;
using Document.Library;
using Encrypt.Library;
using MsSql.DataBase;
using System.Collections.Generic;
using Tool.Model;

namespace Authority.Logic
{
    /// <summary>
    /// 管理员操作逻辑类
    /// </summary>
    public class SysUserServiceImpl : ISysUserService
    {

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<AdminTicket> UserLogin(LoginRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<AdminTicket>();

            if (inputInfo.LoginName != null)
            {
                using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
                {
                    inputInfo.Password = SecurityHelper.GetMD5Hash(inputInfo.Password);

                    var info = con.QuerySet<View_SysUserRoleEntity>()
                        .AndWhere(p => p.sLoginName == inputInfo.LoginName)
                        .Multiple();

                    if (info != null && info.Count > 0)
                    {
                        var result = info.Find(p => p.sLoginName == inputInfo.LoginName && p.sPassword == inputInfo.Password);

                        if (result != null)
                        {
                            if (result.iState == (int)UserState.Normal)
                            {
                                var ticket = result.MapTo<AdminTicket>();

                                resultInfo.Code = ActionCodes.Success;
                                resultInfo.Msg = "操作成功";
                                resultInfo.Data = ticket;
                            }
                            else
                            {
                                resultInfo.Msg = "用户已被冻结，请与管理员联系！";
                            }
                        }
                        else
                        {
                            resultInfo.Msg = "密码错误！";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "账号不存在！";
                    }
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据登录账号获取信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<SysUserEntity> LoadUserByLoginName(string loginName)
        {

            var resultInfo = new ResultJsonInfo<SysUserEntity>();

            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                var userInfo = con.QuerySet<SysUserEntity>()
                    .AndWhere(p => p.sLoginName == loginName)
                    .WithNoLock().Single();

                if (userInfo != null)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "操作成功";
                    resultInfo.Data = userInfo;
                }
                else
                {
                    resultInfo.Msg = "操作失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 上传团购图片（后期把图片上传统一处理）
        /// </summary>
        /// <param name="parametersInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<string> UploadImage(string webRootPath, Dictionary<string, object> inputInfo)
        {
            var result = new ResultJsonInfo<string>();
            var imageBase64 = inputInfo["imageBase64"].ToString();
            var imageType = inputInfo["imageType"].ToString();
            result.Data = ImageHelper.SaveBase64Image(imageBase64, imageType, webRootPath);
            result.Code = ActionCodes.Success;
            return result;
        }

        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<SysUserEntity> SaveUserInfo(UserInfoModifyRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<SysUserEntity>();

            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                var userInfo = con.QuerySet<SysUserEntity>().AndWhere(p => p.sLoginName == inputInfo.LoginName)
                    .WithNoLock().Single();
                userInfo.sUserName = inputInfo.UserName;
                userInfo.iSex = inputInfo.Sex;
                userInfo.sPhone = inputInfo.Phone;
                userInfo.sPicUrl = inputInfo.PicUrl;
                var info = con.CommandSet<SysUserEntity>().Update(userInfo);

                con.QuerySet<SysUserEntity>()
                    .AndWhere(a => a.sLoginName == inputInfo.LoginName)
                    .Top(1)
                    .Select(a =>
                        new SysUserEntity
                        {
                            sUserName = a.sUserName,
                            iSex = a.iSex,
                            sPhone = a.sPhone,
                            sPicUrl = a.sPicUrl
                        }).UpdateSelect(
                    a => new SysUserEntity
                    {
                        sUserName = inputInfo.UserName,
                        iSex = inputInfo.Sex,
                        sPhone = inputInfo.Phone,
                        sPicUrl = inputInfo.PicUrl
                    });

                if (userInfo != null)//&& userInfo.Count>0
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Msg = "操作成功";
                    resultInfo.Data = userInfo;//[0]
                }
                else
                {
                    resultInfo.Msg = "操作失败！";
                }
            }
            return resultInfo;
        }


        /// <summary>
        /// 确认用户修改密码
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<bool> SaveChangePwd(UserPswModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<bool>();

            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {

                inputInfo.OldPsw = SecurityHelper.GetMD5Hash(inputInfo.OldPsw);

                var userInfo = con.QuerySet<SysUserEntity>()
                        .AndWhere(p => p.gCode == inputInfo.Code && p.sPassword== inputInfo.OldPsw)
                       .WithNoLock().Single();
                if (userInfo != null)
                {

                    userInfo.sPassword = SecurityHelper.GetMD5Hash(inputInfo.NewPsw);

                    var resultCount = con.CommandSet<SysUserEntity>().Update(userInfo);

                    if (resultCount > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Msg = "操作成功";
                        resultInfo.Data = resultCount>0;
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败！";
                    }
                }
                else
                {
                    resultInfo.Code = ActionCodes.InvalidOperation;
                    resultInfo.Msg = "旧密码不正确！";
                }
            }
            return resultInfo;
        }
    }
}
